#include "SqList.h"

//测试
void TestSqList() {
    SqList ll;
    pSqList pll = NULL;
    pll = &ll;
    InitList(pll);
    for (int i = 0; i < 10; i++)
        AppendElem(pll, i);
    TraveseList(pll, showElem);
    DeleteElem(pll, 3);
    TraveseList(pll, showElem);
    printf("After clearing the List:\n");
    ClearList(pll);
    TraveseList(pll, showElem);
}

void showElem(ElemType a) {
    printf("The element is: %d\n", a);
}

//初始化线性表（顺序存储）
BOOL InitList(pSqList pList) {
    // pList若为全局指针变量，则为NULL
    // pList若为局部指针变量，则为随机地址值（或者为NULL）
    //使用的时候建议无论是全局变量还是局部变量，均人为初始化为NULL
    if (pList) {
        pList->elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
        if (!pList->elem)
            exit(OVERFLOW);
        pList->length = 0;
        pList->listsize = LIST_INIT_SIZE;
    }
    return TRUE;
}

//销毁线性表
void DestroyList(pSqList pList) {
    if (pList) {
        free(pList->elem);
        pList->length = 0;
        pList->listsize = 0;
    }
}

//清空线性表的元素
void ClearList(pSqList pList) {
    if (pList) {
        free(pList->elem);
        InitList(pList);
    }
}

//判断线性表是否为空
BOOL IsEmpty(SqList List) {
    return List.length <= 0;
}

//获得线性表元素个数
int GetLength(SqList List) {
    return List.length;
}

//获得元素
BOOL GetElem(pSqList pList, int i, ElemType* e) {
    if (i < 0 || i >= pList->length)
        return FALSE;
    else {
        *e = pList->elem[i];
        return TRUE;
    }
}

//在指定位置插入元素
BOOL InsertElem(pSqList pList, int i, ElemType e) {
    if (pList) {
        if (i > pList->length)
            return FALSE;

        //如果空间已经填满，扩容再插入；否则直接插入即可
        if (pList->length == pList->listsize) {
            pList->listsize += LISTINCREMENT;
            ElemType* temp =
                (ElemType*)malloc(pList->listsize * sizeof(ElemType));
            for (int i = 0; i < pList->length; i++)
                temp[i] = pList->elem[i];
            free(pList->elem);
            pList->elem = temp;
        }

        //再完成插入操作
        for (int j = pList->length; j > i; j--)
            pList->elem[j] = pList->elem[j - 1];
        pList->elem[i] = e;

        //更新元素个数
        pList->length++;

        return TRUE;
    }
    return FALSE;
}

//在末尾新增元素
BOOL AppendElem(pSqList pList, ElemType e) {
    if (pList) {
        return InsertElem(pList, pList->length, e);
    }
    return FALSE;
}

//删除指定位置的元素
BOOL DeleteElem(pSqList pList, int i) {
    if (pList) {
        if (i < pList->length || i >= 0) {
            for (int j = i; j < pList->length - 1; j++)
                pList->elem[j] = pList->elem[j + 1];
            pList->length--;
            return TRUE;
        } else {
            return FALSE;
        }
    }
    return FALSE;
}

//遍历线性表
void TraveseList(pSqList pList, void (*visitFunc)(ElemType e)) {
    if (pList) {
        for (int i = 0; i < pList->length; i++) {
            visitFunc(pList->elem[i]);
        }
    }
}
